package com.eventur;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import org.joda.time.DateMidnight;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.util.Log;

public class XmlParser extends DefaultHandler {

	static int counter = 0;
	final int unknownState = 0;
	final int titleState = 1;
	final int linkState = 2;
	final int typeState = 3;
	final int timeState = 4;
	final int venueState = 5;
	final int venueAddressState = 6;
	final int lonState = 7;
	final int latState = 8;
	final int orgState = 9;
	final int imageLinkState=10;
	final int descriptionState = 11;

	int currentState = unknownState;

	Event event = new Event();
	public static ArrayList<Event> eventsList ;

	public static ArrayList<Event> todayEvents = null;
	public static ArrayList<Event> tomorrowEvents= null;
	public static ArrayList<Event> weekEvents= null;

	private static String tomorrow;
	private static SimpleDateFormat formatter = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
	private static DateFormat df = new SimpleDateFormat("MM-dd-yyyy");
	private static Date todaysDate = new java.util.Date();

	private static String tag = "XmlParser";

	private static String saturday ;
	private static String sunday;

	private static Date saturdayDate;
	private static Date sundayDate;

	static DateMidnight todayMidnight = new DateMidnight();
	static DateMidnight tomorrowMidnight = new DateMidnight(todayMidnight.plusDays(1));
	static DateMidnight weekendMidnight = new DateMidnight(todayMidnight.plusDays(7));
	private static SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy HH:mm a");
	private static SimpleDateFormat sdf2 = new SimpleDateFormat("MM-dd-yyyy");


	StringBuffer descriptionAccumulator = new StringBuffer();
	StringBuffer eventDate= new StringBuffer();

	public XmlParser(){
		XmlParser.todayEvents = new ArrayList<Event>();
		XmlParser.tomorrowEvents = new ArrayList<Event>();
		XmlParser.weekEvents = new ArrayList<Event>();
		XmlParser.eventsList = new ArrayList<Event>();
		getWeekendDate();
	}



	private void getWeekendDate() {
		Calendar calendar = Calendar.getInstance();
		//calendar.set(2010,Calendar.JANUARY,19);    
		if(calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)
			calendar.add(Calendar.DATE,3);

		int counter =0;
		while(counter<7){

			if(calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY){
				saturday = formatter.format(calendar.getTime());
				saturdayDate = calendar.getTime();

				calendar.add(Calendar.DATE,1);
				sunday= formatter.format(calendar.getTime());
				sundayDate = calendar.getTime();
				break;
			}

			calendar.add(Calendar.DATE,1);

			//System.out.println("counter:"+counter);
			counter++;

		}

	}

	public int getEventsNumber(){
		return XmlParser.eventsList.size();
	}

	public ArrayList<Event> getEventsList(){
		return eventsList;	
	}
	public void startDocument() throws SAXException{
		System.out.println("Starting to read the document");
	}

	public void endDocument() throws SAXException{
		System.out.println("Number of nodes in the list:"+eventsList.size());
		System.out.println("End of document");
	}

	public void startElement(String uri,String localName, String qName, Attributes attributes) throws SAXException{
		if(localName.equalsIgnoreCase("item")){
			event = new Event();
			return;
		}
		else if(localName.equalsIgnoreCase("title")){
			currentState=titleState;
		}
		else if(localName.equalsIgnoreCase("link")){
			currentState=linkState;
		}
		else if(localName.equalsIgnoreCase("description")){
			descriptionAccumulator.delete(0, descriptionAccumulator.length());
			currentState=descriptionState;
		}
		else if(localName.equalsIgnoreCase("type")){
			currentState=typeState;
		}
		else if(localName.equalsIgnoreCase("s_time")){
			eventDate.delete(0, eventDate.length());

			currentState=timeState;
		}
		else if(localName.equalsIgnoreCase("venue")){
			currentState=venueState;
		}
		else if(localName.equalsIgnoreCase("venue_addr")){
			currentState=venueAddressState;
		}
		else if(localName.equalsIgnoreCase("lon")){
			currentState=lonState;
		}
		else if(localName.equalsIgnoreCase("lat")){
			currentState=latState;
		}
		else if(localName.equalsIgnoreCase("org")){
			currentState=orgState;
		}
		else if(localName.equalsIgnoreCase("img_link")){
			currentState=imageLinkState;
		}
		else{
			currentState=unknownState;
		}
	}
	public void endElement(String uri,String localName, String qName) throws SAXException{
		if(localName.equals("item")){
			System.out.println("Added event to the list with date:"+eventDate);
			event.setEventId(counter++);
			eventsList.add(event);

			if(checkDate(event.getsDate()).contains("today")){
				todayEvents.add(event);
				//Log.i(tag, "Today Event:"+event.getsDate());
			}
			if(checkDate(event.getsDate()).contains("tomorrow")){
				tomorrowEvents.add(event);
				//Log.i(tag, "Tommorrow Event:"+event.getsDate());
			}
			if(checkDate(event.getsDate()).contains("weekend")){
				weekEvents.add(event);
				//Log.i(tag, "Tommorrow Event:"+event.getsDate());
			}


			/*if(checkDate(event.getsDate())=="today"){
				todayEvents.add(event);
				//Log.i(tag, "Today Event:"+event.getsDate());
			}
			else if(checkDate(event.getsDate())=="tomorrow"){
				tomorrowEvents.add(event);
				//Log.i(tag, "Tommorrow Event:"+event.getsDate());
			}
			else if(checkDate(event.getsDate()).contains("today\tomorrow") || checkDate(event.getsDate()).contains("weekend")){
				tomorrowEvents.add(event);
				todayEvents.add(event);
				weekEvents.add(event);

				//Log.i(tag, "Tommorrow Event:"+event.getsDate());
			}

			else if(checkDate(event.getsDate())=="weekend"){
				weekEvents.add(event);
				//Log.i(tag, "Week Event:"+event.getsDate());
			}*/
			System.out.println("--------------------------------------------------------------------");

		}
		else if(localName.equalsIgnoreCase("description")){
			//	System.out.println("Description found is:"+descriptionAccumulator.toString());
			String noHTMLString = descriptionAccumulator.toString().replaceAll("\\<.*?\\>", "");
			noHTMLString = noHTMLString.replace("&nbsp;", " ");
			noHTMLString = noHTMLString.replace("&amp"," ");
			noHTMLString = noHTMLString.replace("&rsquo;","'");
			noHTMLString = noHTMLString.replace("&hellip;", "...");
			//noHTMLString+="\nPlease visit the website for a better view";
			System.out.println("Descr with no html:"+noHTMLString);

			event.setDescription(noHTMLString);
		}
		else if(localName.equalsIgnoreCase("s_time")){
			String date = eventDate.toString().replace("&nbsp", "");
			date = date.replace(";","");
			event.setsDate(date);
			System.out.println("time is:"+date);
		}
	}

	public void characters(char[] ch,int start,int length) throws SAXException{
		String characters = new String(ch,start,length);
		switch(currentState){
		case titleState:
			System.out.println("Title:"+characters);
			event.setTitle(characters);
			break;
		case linkState:
			event.setLink(characters);
			break;
		case descriptionState:
			descriptionAccumulator.append(characters);
			break;
		case typeState:
			event.setType(characters);
			break;
		case timeState:
			eventDate.append(characters);
			break;
		case venueState:
			event.setVenue(characters);
			break;
		case venueAddressState:
			event.setVenueAddress(characters);
			break;
		case lonState:
			event.setLongitude(characters);
			break;
		case latState:
			event.setLatitude(characters);
			break;
		case orgState:
			event.setOrganization(characters);
			break;
		case imageLinkState:
			event.setImageLink(characters.replaceAll(" ","%20"));
			break;

		}
	}

	private static String checkDate(String getsDate){
		String result = "";			

		getsDate = getsDate.replaceAll("&nbsp;","");

		if(getsDate.contains("~")){
			DateMidnight startDate;DateMidnight endDate;
			System.out.println("Event occurs on several dates");
			String seDates[] = getsDate.split("~");
			try {
				startDate = new DateTime(sdf2.parse(seDates[0])).toDateMidnight();
				endDate = new DateTime(sdf2.parse(seDates[1])).toDateMidnight();



				if((todayMidnight.isAfter(startDate) && todayMidnight.isBefore(endDate)) || (todayMidnight.equals(startDate) || todayMidnight.equals(endDate))){
					result+="today";
				}
				if(tomorrowMidnight.isAfter(startDate) && tomorrowMidnight.isBefore(endDate)){
					result+="tomorrow";
				}
				if(todayMidnight.getDayOfWeek() == DateTimeConstants.SATURDAY || todayMidnight.getDayOfWeek() == DateTimeConstants.SUNDAY){
					result+="weekend";
				}

				if(((startDate.getDayOfWeek() ==  DateTimeConstants.SATURDAY) || (startDate.getDayOfWeek() ==  DateTimeConstants.SUNDAY)) && (startDate.isBefore(weekendMidnight)))
				{
					result+="weekend";
				}
				if(((endDate.getDayOfWeek() ==  DateTimeConstants.SATURDAY) || (endDate.getDayOfWeek() ==  DateTimeConstants.SUNDAY)) && (endDate.isBefore(weekendMidnight)))
				{
					result+="weekend";
				}


			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
		}
		else{
			System.out.println("Single Event Date");
			try {
				DateMidnight eventMidnight = new DateTime(sdf.parse(getsDate)).toDateMidnight(); 
				if(eventMidnight.equals(todayMidnight)){
					result+="today";
				}
				if(eventMidnight.equals(tomorrowMidnight)){
					result+="tomorrow";
				}
				if(((eventMidnight.getDayOfWeek() ==  DateTimeConstants.SATURDAY) || (eventMidnight.getDayOfWeek() ==  DateTimeConstants.SUNDAY)) && (eventMidnight.isBefore(weekendMidnight))){
					result+="weekend";
				}


			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return result;

	}

	/*private static String checkDate(String getsDate) {
		Calendar calendar = Calendar.getInstance();

		Date date = null;
		String formattedDate = formatter.format(todaysDate);
		System.out.println("today date:"+formattedDate);

		calendar.add(Calendar.DATE,0);

		date =  calendar.getTime();
		calendar.add(Calendar.DATE, 1);
		//System.out.println("adding 1 day for tomorrow");
		date = calendar.getTime();
		Date tomorrowDate = date;
		String flag ="";
		tomorrow = formatter.format(date);
		Date eventStartDate = null;
		Date eventEndDate = null;
		System.out.println("event date:"+getsDate);
		if(getsDate.contains("~")){
			System.out.println("Its a long date");
			try{
				String [] detailedDate = new String [2];
				detailedDate = getsDate.split("~");

				eventStartDate = df.parse(detailedDate[0]);            
				System.out.println("Start = " + df.format(eventStartDate));
				eventEndDate = df.parse(detailedDate[1]);            
				System.out.println("End = " + df.format(eventEndDate));
			}
			catch(Exception e){

			}
			if(todaysDate.equals(eventStartDate) || todaysDate.equals(eventEndDate)){
				//return("Either start or end day");
				return "today";

			}
			else if(todaysDate.after(eventStartDate)&& todaysDate.before(eventEndDate)){
				//return "its in the middle";
				if(eventStartDate.equals(tomorrow) || eventEndDate.equals(tomorrow))
					flag= "today\tomorrow";
				else if(tomorrowDate.after(eventStartDate)&& tomorrowDate.before(eventEndDate))
					flag = "today\tomorrow";
				else if(saturdayDate.after(eventStartDate) && saturdayDate.before(eventEndDate) || sundayDate.after(eventStartDate) && sundayDate.before(eventEndDate) ){
				flag +="weekend";
				System.out.println(flag);
				return flag;

				//return "today";

			}
			else if(eventStartDate.equals(tomorrow) || eventEndDate.equals(tomorrow)){
				System.out.println("tomorrow");
				return "tomorrow";
			}
			else if(tomorrowDate.after(eventStartDate) && tomorrowDate.before(eventEndDate)){
				System.out.println("tomorrow");
				return "tomorrow";
			}
			else if(eventStartDate.equals(saturdayDate) || eventEndDate.equals(saturdayDate) || eventStartDate.equals(sundayDate) || eventEndDate.equals(sundayDate)){
				System.out.println("weekend");
				return "weekend";
			}

			else if(!saturdayDate.after(eventStartDate) && !saturdayDate.before(eventEndDate) || !sundayDate.after(eventStartDate) && !sundayDate.before(eventEndDate) ){
				System.out.println("weekend");
				return "weekend";
			}
			return "future";



		}

		else{
			System.out.println("one day event");
			System.out.println("tomorrow date:"+tomorrow.substring(0,10));
			System.out.println("event date substring:"+getsDate.substring(0,10));


			if(getsDate.substring(0, 10).equalsIgnoreCase(formattedDate.substring(0, 10))){
				System.out.println("Its today event");
				return "today";
			}
			else if(getsDate.substring(0, 10).equalsIgnoreCase(tomorrow.substring(0, 10))){
				System.out.println("Its tomorrow event");
				return "tomorrow";
			}
			else if(getsDate.substring(0, 10).equalsIgnoreCase(saturday.substring(0, 10)) || getsDate.substring(0, 10).equalsIgnoreCase(sunday.substring(0, 10))){
				System.out.println("Its in weekend");
				return "weekend";
			}
			return "future";

		}
	}
	 */



}

